//
//  LSUserIconViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/20.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSUserIconViewController.h"
#import "HXPhotoPicker.h"
#import <Photos/Photos.h>

static const CGFloat kPhotoViewMargin = 0.0;

@interface LSUserIconViewController () <UIScrollViewDelegate, HXPhotoViewDelegate>
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIScrollView *iconImageScrollView;
@property (nonatomic, assign) BOOL zoomOut_In;

@property (strong, nonatomic) HXPhotoManager *manager;
@property (strong, nonatomic) HXPhotoView *photoView;
@property (strong, nonatomic) UIScrollView *photoscrollView;
@property (strong, nonatomic) HXDatePhotoToolManager *toolManager;

@property (nonatomic, strong) NSArray *photosArr;
@property (nonatomic, strong) NSArray *photoNameArr;
@property (nonatomic, strong) NSArray *photoFileNameArr;
@end

@implementation LSUserIconViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人头像";
    UIBarButtonItem *changeIconItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreItemClick)];
    self.navigationItem.rightBarButtonItem = changeIconItem;
    _iconImageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, 0.0,ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
    _iconImageScrollView.backgroundColor = [UIColor grayColor];
    _iconImageScrollView.delegate = self;
    if (@available(iOS 11.0, *)) {
        _iconImageScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    [self.view addSubview:_iconImageScrollView];
    //_scrollview可以拖动的范围
    float x=0;
    float y=(ScreenHeight-SafeAreaTopHeight-ScreenWidth)/2;
    float width = ScreenWidth;
    float height = ScreenWidth;
    _iconImageView = [[UIImageView alloc] initWithImage:self.nowIconImage];
    [_iconImageView setFrame:CGRectMake(x, y, width, height)];
    [_iconImageScrollView addSubview:_iconImageView];
    UITapGestureRecognizer* tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesAction:)];//给imageview添加tap手势
    tap.numberOfTapsRequired = 2;//双击图片执行tapGesAction
    _iconImageView.userInteractionEnabled=YES;
    [_iconImageView addGestureRecognizer:tap];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    [_iconImageView addGestureRecognizer:longPress];
    [_iconImageScrollView setMinimumZoomScale:1.0];//设置最小的缩放大小
    _iconImageScrollView.maximumZoomScale = 3.0;//设置最大的缩放大小
    _zoomOut_In = YES;//控制点击图片放大或缩小
    
    
    UIScrollView *photoscrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(15, 10, 70*3+kPhotoViewMargin*2, 70)];
    photoscrollView.alwaysBounceVertical = YES;
    photoscrollView.alpha = 0.0;//在这里添加这个view纯粹是为了使用框架，并不实际需要这个view
    [self.view addSubview:photoscrollView];
    self.photoscrollView = photoscrollView;
    CGFloat photoscrollViewWidth = photoscrollView.frame.size.width;
    HXPhotoView *photoView = [HXPhotoView photoManager:self.manager];
    photoView.frame = CGRectMake(kPhotoViewMargin, kPhotoViewMargin, photoscrollViewWidth - kPhotoViewMargin * 2, 0);
    photoView.delegate = self;
    photoView.outerCamera = NO;
    photoView.backgroundColor = [UIColor whiteColor];
    [photoscrollView addSubview:photoView];
    self.photoView = photoView;
}

- (void)moreItemClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    WS
    [alert addActionTarget:alert title:@"从手机相册选择" color:NAV_COLOR action:^(UIAlertAction *action) {
        [weakSelf.photoView goPhotoViewController];
    }];
    [alert addActionTarget:alert title:@"保存图片" color:NAV_COLOR action:^(UIAlertAction *action) {
        [weakSelf saveImageToAlbum];
    }];
    [alert addCancelActionTarget:alert color:NAV_COLOR title:@"取消"];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)longPressAction:(UIGestureRecognizer*)gestureRecognizer {
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan) return;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    WS
    [alert addActionTarget:alert title:@"保存图片" color:NAV_COLOR action:^(UIAlertAction *action) {
        [weakSelf saveImageToAlbum];
    }];
    [alert addCancelActionTarget:alert color:NAV_COLOR title:@"取消"];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)saveImageToAlbum {
    /*
     PHAsset : 一个PHAsset对象就代表一个资源文件,比如一张图片
     PHAssetCollection : 一个PHAssetCollection对象就代表一个相册
     */
    WS
    __block NSString *assetId = nil;
    // 1. 存储图片到"相机胶卷"
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 这个block里保存一些"修改"性质的代码
        // 新建一个PHAssetCreationRequest对象, 保存图片到"相机胶卷"
        // 返回PHAsset(图片)的字符串标识
        assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:weakSelf.nowIconImage].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            NSLog(@"保存图片到相机胶卷中失败，原因是%@",error.localizedDescription);
            [MBProgressHUD showTipMessageInWindow:@"保存失败"];
            return;
        }
        [MBProgressHUD showTipMessageInWindow:@"保存成功"];
        NSLog(@"成功保存图片到相机胶卷中");
        //再将照片保存至指定自定义相册
        //        // 2. 获得相册对象
        //        PHAssetCollection *collection = [self collection];
        //
        //        // 3. 将“相机胶卷”中的图片添加到新的相册
        //        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
        //
        //            // 根据唯一标示获得相片对象
        //            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
        //            // 添加图片到相册中
        //            [request addAssets:@[asset]];
        //        } completionHandler:^(BOOL success, NSError * _Nullable error) {
        //            if (error) {
        //                BSLog(@"添加图片到相册中失败");
        //                return;
        //            }
        //
        //            BSLog(@"成功添加图片到相册中");
        //            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        //                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        //            }];
        //        }];
    }];
}

-(void)tapGesAction:(UIGestureRecognizer*)gestureRecognizer {//手势执行事件
    float newscale=0.0;
    if (_zoomOut_In) {
        newscale = (ScreenHeight-SafeAreaTopHeight)/ScreenWidth;
        _zoomOut_In = NO;
    }else{
        newscale = 1.0;
        _zoomOut_In = YES;
    }
    CGRect zoomRect = [self zoomRectForScale:newscale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    NSLog(@"zoomRect:%@",NSStringFromCGRect(zoomRect));
    [ _iconImageScrollView zoomToRect:zoomRect animated:YES];//重新定义其cgrect的x和y值
}

//当UIScrollView尝试进行缩放的时候调用
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _iconImageView;
}

//当缩放完毕的时候调用
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    NSLog(@"结束缩放 - %f", scale);
}

//当正在缩放的时候调用
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIImageView *subView = _iconImageView;
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                 scrollView.contentSize.height * 0.5 + offsetY);
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
    CGRect zoomRect;
    zoomRect.size.height = [_iconImageScrollView frame].size.height / scale;
    zoomRect.size.width = [_iconImageScrollView frame].size.width / scale;
    zoomRect.origin.x= center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y= center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}

#pragma mark - 图像选择控制器代理实现
- (HXDatePhotoToolManager *)toolManager {
    if (!_toolManager) {
        _toolManager = [[HXDatePhotoToolManager alloc] init];
    }
    return _toolManager;
}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.navBarBackgroudColor = nil;
        _manager.configuration.statusBarStyle = UIStatusBarStyleLightContent;
        _manager.configuration.sectionHeaderTranslucent = YES;
        _manager.configuration.cellSelectedBgColor = nil;
        _manager.configuration.selectedTitleColor = nil;
        _manager.configuration.openCamera = YES;
        _manager.configuration.lookLivePhoto =  NO;
//        _manager.configuration.photoMaxNum = 1;
//        _manager.configuration.videoMaxNum = 0;
//        _manager.configuration.maxNum = 3;
//        _manager.configuration.videoMaxDuration = 500.f;
        _manager.configuration.saveSystemAblum = YES;
//        _manager.configuration.reverseDate = YES;
        _manager.configuration.showDateSectionHeader = NO;
        _manager.configuration.selectTogether = YES;
        _manager.configuration.singleSelected = YES;
        _manager.configuration.albumListTableView = ^(UITableView *tableView) {
//            NSSLog(@"%@",tableView);
        };
        _manager.configuration.singleJumpEdit = YES;
        _manager.configuration.movableCropBox = YES;
        _manager.configuration.movableCropBoxEditSize = YES;
        _manager.configuration.defaultClipProportionValue1 = 1;
        _manager.configuration.defaultClipProportionValue2 = 1;
        _manager.configuration.rightBarButtonItemTintColor = [UIColor whiteColor];
        _manager.configuration.themeColor = NAV_COLOR;
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        
        
        //        _manager.configuration.rowCount = 3;
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        
        __weak typeof(self) weakSelf = self;
        //        _manager.configuration.replaceCameraViewController = YES;
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
    }
    return _manager;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    HXPhotoModel *model;
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        model = [HXPhotoModel photoModelWithImage:image];
        if (self.manager.configuration.saveSystemAblum) {
            [HXPhotoTools savePhotoToCustomAlbumWithName:self.manager.configuration.customAlbumName photo:model.thumbPhoto];
        }
    }else  if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *url = info[UIImagePickerControllerMediaURL];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
        float second = 0;
        second = urlAsset.duration.value/urlAsset.duration.timescale;
        model = [HXPhotoModel photoModelWithVideoURL:url videoTime:second];
        if (self.manager.configuration.saveSystemAblum) {
            [HXPhotoTools saveVideoToCustomAlbumWithName:self.manager.configuration.customAlbumName videoURL:url];
        }
    }
    if (self.manager.configuration.useCameraComplete) {
        self.manager.configuration.useCameraComplete(model);
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal {
    NSSLog(@"所有:%ld - 照片:%ld - 视频:%ld",allList.count,photos.count,videos.count);
    NSSLog(@"所有:%@ - 照片:%@ - 视频:%@",allList,photos,videos);
    
    [HXPhotoTools selectListWriteToTempPath:allList requestList:^(NSArray *imageRequestIds, NSArray *videoSessions) {
        NSSLog(@"requestIds - image : %@ \nsessions - video : %@",imageRequestIds,videoSessions);
    } completion:^(NSArray<NSURL *> *allUrl, NSArray<NSURL *> *imageUrls, NSArray<NSURL *> *videoUrls) {
        NSSLog(@"allUrl - %@\nimageUrls - %@\nvideoUrls - %@",allUrl,imageUrls,videoUrls);
        NSMutableArray *photosArrM = [[NSMutableArray alloc] init];
        NSMutableArray *photoNameArrM = [[NSMutableArray alloc] init];
        NSMutableArray *photoFileNameArrM = [[NSMutableArray alloc] init];
        for (NSURL *imageUrl in imageUrls) {
            NSArray *arr = [imageUrl.absoluteString componentsSeparatedByString:@"/"];
            NSArray *arrr = [arr.lastObject componentsSeparatedByString:@"."];
            [photoNameArrM addObject:arrr.firstObject];
            [photoFileNameArrM addObject:arr.lastObject];
            NSData *uploadData = [NSData dataWithContentsOfURL:imageUrl];
            UIImage *image = [UIImage imageWithData:uploadData];
            [photosArrM addObject:image];
        }
        self.photoNameArr = photoNameArrM.copy;
        self.photoFileNameArr = photoFileNameArrM.copy;
        self.photosArr = photosArrM.copy;
        self.iconImageView.image = self.photosArr.firstObject;
    } error:^{
        NSSLog(@"失败");
    }];
}

- (void)photoView:(HXPhotoView *)photoView deleteNetworkPhoto:(NSString *)networkPhotoUrl {
    NSSLog(@"%@",networkPhotoUrl);
}

- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame {
    NSSLog(@"%@",NSStringFromCGRect(frame));
    self.photoscrollView.contentSize = CGSizeMake(self.photoscrollView.frame.size.width, CGRectGetMaxY(frame) + kPhotoViewMargin);
    
}

- (void)photoView:(HXPhotoView *)photoView currentDeleteModel:(HXPhotoModel *)model currentIndex:(NSInteger)index {
    NSSLog(@"%@ --> index - %ld",model,index);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
